package com.wyl.java.thread_.create_;

import cn.hutool.core.util.RandomUtil;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程的创建
 * 方法二：实现Runnable接口，重写run方法
 * 启动Runnable常用有2种方法
 * 1.使用Thread运行
 * 2.使用线程池运行
 * @author 吴宇亮 on 2023/3/24 15:03
 */
public class CreateThread02 implements Runnable {

    public static void main(String[] args) {
        Thread thread01 = new Thread(new CreateThread02());
        Thread thread02 = new Thread(new CreateThread02());
        // 运行Runnable的方法一：使用Thread去运行
//        thread01.start();
//        thread02.start();

        // 运行Runnable的方法二：使用线程池去运行
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.execute(thread01);
        executorService.execute(thread02);
        executorService.shutdown();
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                if (RandomUtil.randomBoolean()) {
                    Thread.sleep(RandomUtil.randomLong(500, 1200));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
        }
    }
}
